package shining365.programmableweb.data.app;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;

public class ApiActiveness {

	public ApiActiveness(Date oldDate, Date newDate) throws IOException, JAXBException {
		if (oldDate.compareTo(newDate) > 0) {
			throw new IllegalArgumentException("oldDate must be before newDate");
		}
		
		oldData = new AppData(oldDate);
		newData = new AppData(newDate);
	}
	
	public Map<String, Double> getApiActiveness() {
		Map<String, Double> oldApi2strength = new HashMap<String, Double>();
		Map<String, Double> newApi2strength = new HashMap<String, Double>();
		for (int i = 0; i < oldData.apis.size(); i++) {
			oldApi2strength.put(
					oldData.apis.get(i).getUrl(), oldData.strengths[i]);
		}
		for (int i = 0; i < newData.apis.size(); i++) {
			newApi2strength.put(
					newData.apis.get(i).getUrl(), newData.strengths[i]);
		}
		
		double sumDelta = 0;
		Map<String, Double> api2delta = new HashMap<String, Double>();
		for (Entry<String, Double> e : newApi2strength.entrySet()) {
			Double oldStrength = oldApi2strength.get(e.getKey());
			double delta = 
				oldStrength == null ? e.getValue() : e.getValue() - oldStrength;
			api2delta.put(e.getKey(), delta);
			sumDelta += delta;
		}
		
		Map<String, Double> api2activeness = new HashMap<String, Double>();
		for (Entry<String, Double> e : api2delta.entrySet()) {
			api2activeness.put(e.getKey(), e.getValue() / sumDelta);
		}
		
		return api2activeness;
	}
	
	private static class AppData extends AppBasic {
		public AppData(Date endDate) throws IOException, JAXBException {
			super(endDate, false, OrderBy.USE_COUNT);
		}
	}
	
	private final AppData oldData;
	private final AppData newData;
	
	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(ApiActiveness.class);
}
